import axios from 'axios'
import { ElMessage } from 'element-plus'

/**
 * Logo生成HTTP轮询工具类
 * 供其他Vue页面使用，不依赖WebSocket
 */
class LogoPollingService {
  constructor() {
    this.pollingIntervals = new Map() // 存储每个用户的轮询定时器
    this.maxPollingTime = 300000 // 最大轮询时间5分钟
    this.pollingInterval = 2000 // 轮询间隔2秒
  }

  /**
   * 开始轮询Logo生成进度
   * @param {number} userId - 用户ID
   * @param {function} onProgress - 进度回调函数
   * @param {function} onComplete - 完成回调函数
   * @param {function} onError - 错误回调函数
   */
  startPolling(userId, onProgress, onComplete, onError) {
    if (this.pollingIntervals.has(userId)) {
      console.warn(`[Logo轮询] 用户 ${userId} 的轮询已在进行中`)
      return
    }

    console.log(`[Logo轮询] 开始轮询用户 ${userId} 的Logo生成进度`)
    
    const startTime = Date.now()
    const token = localStorage.getItem('token')
    const headers = token ? { 'Authorization': `Bearer ${token}` } : {}

    const poll = async () => {
      try {
        // 检查是否超时
        if (Date.now() - startTime > this.maxPollingTime) {
          this.stopPolling(userId)
          if (onError) {
            onError('Logo生成超时，请稍后重试')
          }
          return
        }

        const response = await axios.get(
          `http://localhost:8000/api/ai/logo-progress/${userId}/`,
          { headers }
        )

        if (response.data.success) {
          const data = response.data.data
          
          // 调用进度回调
          if (onProgress) {
            onProgress(data)
          }

          // 检查是否完成
          if (data.result && data.result.success !== undefined) {
            this.stopPolling(userId)
            if (onComplete) {
              onComplete(data.result)
            }
            return
          }
        } else {
          console.error(`[Logo轮询] 轮询失败，用户ID: ${userId}:`, response.data.message)
        }
      } catch (error) {
        console.error(`[Logo轮询] 轮询错误，用户ID: ${userId}:`, error)
        
        // 如果是网络错误，继续轮询；如果是其他错误，停止轮询
        if (error.code === 'NETWORK_ERROR' || error.code === 'ECONNABORTED') {
          // 网络错误，继续轮询
          return
        } else {
          this.stopPolling(userId)
          if (onError) {
            onError('轮询过程中发生错误，请稍后重试')
          }
          return
        }
      }

      // 继续轮询
      const intervalId = setTimeout(poll, this.pollingInterval)
      this.pollingIntervals.set(userId, intervalId)
    }

    // 开始第一次轮询
    poll()
  }

  /**
   * 停止轮询
   * @param {number} userId - 用户ID
   */
  stopPolling(userId) {
    const intervalId = this.pollingIntervals.get(userId)
    if (intervalId) {
      clearTimeout(intervalId)
      this.pollingIntervals.delete(userId)
      console.log(`[Logo轮询] 停止轮询用户 ${userId} 的Logo生成进度`)
    }
  }

  /**
   * 停止所有轮询
   */
  stopAllPolling() {
    for (const [userId, intervalId] of this.pollingIntervals) {
      clearTimeout(intervalId)
      console.log(`[Logo轮询] 停止轮询用户 ${userId} 的Logo生成进度`)
    }
    this.pollingIntervals.clear()
  }

  /**
   * 检查是否正在轮询
   * @param {number} userId - 用户ID
   * @returns {boolean}
   */
  isPolling(userId) {
    return this.pollingIntervals.has(userId)
  }

  /**
   * 获取轮询状态
   * @returns {object}
   */
  getPollingStatus() {
    return {
      activePolling: Array.from(this.pollingIntervals.keys()),
      count: this.pollingIntervals.size
    }
  }
}

// 创建单例实例
const logoPollingService = new LogoPollingService()

export default logoPollingService
